package com.onpositive.realmview.basic;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.onpositive.semantic.model.api.command.ICommand;
import com.onpositive.semantic.model.api.command.ICommandListener;
import com.onpositive.semantic.model.api.command.SimpleOneArgCommand;

public class ProxyMapCommandExecutor implements IListenableCommandExecutor {

	private final Map<String, Object> valueMap;
	List<ICommandListener> listeners = new ArrayList<ICommandListener>();

	public ProxyMapCommandExecutor(Map<String, Object> valueMap) {
		this.valueMap = valueMap;
	}

	@Override
	public void execute(ICommand cmd) {
		if (cmd instanceof SimpleOneArgCommand && SimpleOneArgCommand.SET_VALUE.equals(((SimpleOneArgCommand) cmd).getKind())){
			valueMap.put(((SimpleOneArgCommand) cmd).getProperty().getId(), ((SimpleOneArgCommand) cmd).getValue());
			commandExecuted(cmd);
		}

	}

	private void commandExecuted(ICommand cmd) {
		for (ICommandListener listener : listeners) {
			listener.commandExecuted(cmd);
		}
	}

	@Override
	public boolean addCommandListener(ICommandListener commandListener) {
		return listeners.add(commandListener);
	}

	@Override
	public boolean removeCommandListener(ICommandListener commandListener) {
		return listeners.remove(commandListener);
	}
	
}
